import { fileURLToPath, URL } from 'node:url'

import { defineConfig, loadEnv } from 'vite'
import type { ConfigEnv, UserConfig, ProxyOptions } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import vueDevTools from 'vite-plugin-vue-devtools'
import { createHtmlPlugin } from 'vite-plugin-html'
import tailwindcss from '@tailwindcss/vite'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { viteMockServe } from 'vite-plugin-mock'
// vs code 编辑器配置
import ViteMonacoPlugin from 'vite-plugin-monaco-editor-esm'
import { webUpdateNotice } from '@plugin-web-update-notification/vite';
import settings from './src/settings'

// https://vite.dev/config/
export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
  const root = process.cwd()
  const env = loadEnv(mode, root)

  const { VITE_PROXY, VITE_PORT, VITE_OPEN } = env

  return {
    base: './',
    plugins: [
      vue(),
      vueJsx(),
      vueDevTools(),
      tailwindcss(),
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
      ViteMonacoPlugin({
        languageWorkers: ["editorWorkerService", "typescript", "json", "html"],
      }),
      viteMockServe({
        mockPath: './src/services/mock',
      }),
      createHtmlPlugin({
        minify: true,
        /**
         * Data that needs to be injected into the index.html ejs template
         */
        inject: {
          data: {
            title: settings.title,
            lang: settings.lang,
          },
        },
      }),
      webUpdateNotice({
        // 设置版本类型，可取值如 'build_timestamp'（构建时间戳） 、'git_commit_hash'（Git提交哈希）等
        versionType: 'build_timestamp',
        // 自定义通知弹窗的相关属性
        notificationProps: {
          title: '📢 系统更新', // 通知标题
          description: '为了您更好的体验我们升级了系统，请您刷新页面体验最新版本,如需自己刷新,请使用shift加f5进行刷新', // 通知描述
          buttonText: '刷新', // 刷新按钮文本
          dismissButtonText: "忽略", // 忽略按钮文本
        },
      }),
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    server: {
      host: '0.0.0.0',
      port: Number(VITE_PORT),
      open: VITE_OPEN === 'true',
      cors: true,
      // Load proxy configuration from .env.development
      proxy: (function (list: string) {
        const proxyList = list ? JSON.parse(list) : []
        const ret: Record<string, ProxyOptions> = {}
        for (const [prefix, target] of proxyList) {
          const httpsRE = /^https:\/\//
          const isHttps = httpsRE.test(target)
          ret[prefix] = {
            target: target,
            changeOrigin: true,
            ws: true,
            rewrite: (path) => path.replace(new RegExp(`^${prefix}`), ''),
            // https is require secure=false
            ...(isHttps ? { secure: false } : {}),
          }
        }
        return ret
      })(VITE_PROXY),
    },
  }
})
